package com.mvd.app.ac2019;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iceteck.silicompressorr.SiliCompressor;
import com.kongzue.dialog.v3.WaitDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac2020.DiaoDuActivity;
import com.mvd.app.activity.BaseActivity;
import com.mvd.app.activity.DaiJianCarsActivity;
import com.mvd.app.activity.PermissionUtils;
import com.mvd.app.activity.PreChereckActivity;
import com.mvd.app.activity.SettingActivity;
import com.mvd.app.activity.TianjinActivity;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.Utils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.model.UserAccountModel;
import com.mvd.app.model.VideoUploadModel;
import com.mvd.app.upload.MyUploadService;
import com.mvd.app.upload.Util;
import com.vincent.videocompressor.VideoCompress;
import com.werb.permissionschecker.PermissionChecker;
import com.zolad.videoslimmer.VideoSlimmer;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.os.Environment.getExternalStorageState;

/**
 * 新版进入后的第一个页面
 * 导航页
 * 四个大按钮
 **/
public class FirstActivity extends BaseActivity {

    @BindView(R.id.ac_first_waijian)
    TextView acFirstWaijian;
    @BindView(R.id.ac_first_dipandongtai)
    TextView acFirstDipandongtai;
    @BindView(R.id.ac_first_lushi)
    TextView acFirstLushi;
    @BindView(R.id.ac_login_view_m123)
    TextView acLoginViewM123;
    @BindView(R.id.ac_first_setting)
    TextView acFirstSetting;
    @BindView(R.id.ac_first_denglu)
    TextView acFirstDenglu;
    @BindView(R.id.ac_first_diaodu)
    TextView acFirstDiaodu;
    @BindView(R.id.first_imageView)
    ImageView firstImageView;
    @BindView(R.id.ac_first_rl_1)
    RelativeLayout acFirstRl1;
    @BindView(R.id.ac_first_yujian)
    TextView acFirstYujian;
    @BindView(R.id.ac_first_rl_tianjin)
    RelativeLayout acFirstRlTianjin;
    @BindView(R.id.ac_first_ll)
    LinearLayout acFirstLl;
    @BindView(R.id.ac_first_setting2)
    TextView acFirstSetting2;
    @BindView(R.id.ac_first_tianjin)
    TextView acFirstTianjin;
    @BindView(R.id.ac_first_setting3)
    TextView acFirstSetting3;
    @BindView(R.id.ac_first_rl_tianjin2)
    RelativeLayout acFirstRlTianjin2;
    @BindView(R.id.ac_first_qingdao)
    TextView acFirstQingdao;
    @BindView(R.id.ac_first_qingdao2)
    TextView acFirstQingdao2;
    @BindView(R.id.ac_first_rl_qingdao)
    LinearLayout acFirstRlQingdao;

    private FirstActivity instance;
    public static String[] permissionArray = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.VIBRATE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.RECORD_AUDIO,
    };

    private PermissionChecker permissionChecker;
    List<VideoUploadModel> VideoUploadModelList = new ArrayList<>();
    private String Login_name = "", login_IDNumber, login_username;//当前登录的检测员的名字
    private long startTime, endTime;


    private UserAccountModel UserAccountModel_model;
    //    private Compressor mCompressor;
    private String currentOutputVideoPath = "";//压缩后的视频地址
    public static final String PATH =
            Environment.getExternalStorageDirectory().getAbsolutePath() + "/apeng/";
    private String videoTime = "";//获取视频时长
    private int videoWidth = 0;//获取视频的宽度
    private int videoHeight = 0;//获取视频的高度
    private int videoGotation = 0;//获取视频的角度
    private Bitmap mBitMap;
    private Double videoLength = 0.00;//视频时长 s
    private Handler handler = new Handler();
    MyRunnable myRunnable = new MyRunnable();//定义MyRunnable的对象；
    VideoUploadModel model = null;

//    private CustomProgressDialog mProcessingDialog;

//    private String mVideoPath = "";//原视频地址

    //    public static final String PATH =
//            Environment.getExternalStorageDirectory().getAbsolutePath() + "/apeng/";
    class MyRunnable implements Runnable {//内部类实现Runnable接口；

        @Override
        public void run() {//还是在Runnable重写的run()方法中更新界面；
//            text.setText("使用Handler更新了界面");
//            videoCompress(model.getSize(), model.getZp(), model);
//            video_VideoProcessor(model.getSize(), model.getZp(), model);
//            videoCompress_low(model.getSize(), model.getZp(), model);
//            videoCompress_medium(model.getSize(), model.getZp(), model);
            siliCompressor(model.getSize(), model.getZp(), model);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        ButterKnife.bind(this);
        instance = this;
        PermissionUtils.checkPermissionArray(this, permissionArray, 2);
        String logStrf = "\n" + "onCreate-----FirstActivity-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        permissionChecker = new PermissionChecker(this); // initialize，must need

        if (permissionChecker.isLackPermissions(permissionArray)) {
            permissionChecker.requestPermissions();
            UtilsLog.e("请求录像权限失败===");
        } else {
            // startVideo();
            UtilsLog.e("请求录像权限成功===");
        }
//        if(getIntent().getExtras()!=null){
        Login_name = getIntent().getExtras().getString("login_UserID", "");
        login_IDNumber = getIntent().getExtras().getString("login_IDNumber", "");
        login_username = getIntent().getExtras().getString("login_username", "");
        UserAccountModel_model = (UserAccountModel) getIntent().getSerializableExtra("UserAccountModel_model");
        UtilsLog.e("FirstActivity-----UserAccountModel_model===" + UserAccountModel_model.toString());
//        }
//        imageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                luxiang();
//                String filePath = Environment.getExternalStorageDirectory().getPath() + "/myvideo/" + "111111.mp4";
////                String filePath = FileManager.get().getRootFile() + "/msc/"  + "111111.mp4";   // 保存路径
//                Uri uri = Uri.fromFile(new File(filePath));   // 将路径转换为Uri对象
//                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  // 表示跳转至相机的录视频界面
//                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);    // MediaStore.EXTRA_VIDEO_QUALITY 表示录制视频的质量，从 0-1，越大表示质量越好，同时视频也越大
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);    // 表示录制完后保存的录制，如果不写，则会保存到默认的路径，在onActivityResult()的回调，通过intent.getData中返回保存的路径
//                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30);   // 设置视频录制的最长时间
//                startActivityForResult(intent, 1);  // 跳转
//            }
//        });
        bindService();


        String quality = SharedPreferencesUtils.getVideoQuality(this);
        UtilsLog.e("FirstActivity---视频画质==" + quality);

        getDB();
        String str0 = "", str1 = "";
        str0 = CommonUtils.getIMEI(this, 0);
        str1 = CommonUtils.getIMEI(this, 1);
        UtilsLog.e("手机IMEI---1---" + str0);
        UtilsLog.e("手机IMEI---2---" + str1);
//

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String logStrf = "\n" + "onDestroy-----FirstActivity-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        unBindService();
    }

    @Override
    protected void onResume() {
        super.onResume();
        UtilsLog.e("天津地区开关==" + SharedPreferencesUtils.getTianJinVersion(instance));
        if (SharedPreferencesUtils.getTianJinVersion(instance)) {
            acFirstRlTianjin2.setVisibility(View.VISIBLE);
        } else {
            acFirstRlTianjin2.setVisibility(View.GONE);
        }
        if (SharedPreferencesUtils.getQingDao(instance)) {
            acFirstRlQingdao.setVisibility(View.VISIBLE);
        } else {
            acFirstRlQingdao.setVisibility(View.GONE);
        }
    }

    /**
     * Get db.
     * 查询数据库
     * 获取没有上传完成的视频
     */
    void getDB() {
        VideoUploadModelList = VideoUploadModel.find(VideoUploadModel.class, "statement=?", "0");
        if (VideoUploadModelList != null && VideoUploadModelList.size() > 0) {
//            initFile();
//            initVideo();
            for (int i = 0; i < VideoUploadModelList.size(); i++) {
                UtilsLog.e("VideoUploadModelList==" + i + "===" + VideoUploadModelList.get(i));
                String logStr22 = "\n" + "getDB()---录像路径---" + "\n" + "DB--data==" + "\n" +
                        VideoUploadModelList.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
                model = VideoUploadModelList.get(i);
//                videoCompress2(model.getSize(), model.getZp(), model);

                String quality = SharedPreferencesUtils.getVideoQuality(this);
                UtilsLog.e("FirstActivity---视频画质==" + quality);
                if (SharedPreferencesUtils.getDongBeiVersion(this)) {
                    new Thread() {

                        @Override
                        public void run() {
                            handler.post(myRunnable);//调用Handler.post方法；
                        }
                    }.start();
//                video_VideoProcessor(model.getSize(), model.getZp(), model);
                } else {
                    videoCompress_no(model);
                }
//                videoCompress_no(model);
//                if (quality.equals("低")) {
//                    videoCompress_low(model.getSize(), model.getZp(), model);
//                } else if (quality.equals("中")) {
//                    videoCompress_medium(model.getSize(), model.getZp(), model);
//                } else if (quality.equals("高")) {
//                    videoCompress_high(model.getSize(), model.getZp(), model);
//                } else if (quality.equals("无")) {
//                    videoCompress_no(model);
//                } else {
////                    startCompress(model);
//                }
            }
        }
        List<VideoUploadModel> VideoUploadModelList2 = new ArrayList<>();
        VideoUploadModelList2 = VideoUploadModel.find(VideoUploadModel.class, "statement=?", "0");
        if (VideoUploadModelList2 != null && VideoUploadModelList2.size() > 0) {
            for (int i = 0; i < VideoUploadModelList2.size(); i++) {
                long id = VideoUploadModelList2.get(i).getId();
                VideoUploadModel user = VideoUploadModel.findById(VideoUploadModel.class, id);
                user.delete();
            }
        }
    }

//    void video_VideoProcessor(String videoUriString, String videoPath, final VideoUploadModel model) {
//        UtilsLog.e("video_VideoProcessor=11==videoUriString==" + videoUriString);
//        UtilsLog.e("video_VideoProcessor=11==videoPath==" + videoPath);
//        try {
//            VideoProcessor.processor(this)
//                    .input(videoUriString)
//                    .output(videoPath)
//                    .outWidth(800)
//                    .outHeight(800)
//                    .progressListener(new VideoProgressListener() {
//                        @Override
//                        public void onProgress(float progress) {
//                            UtilsLog.e("video_VideoProcessor===progress==" + progress);
//                        }
//                    })
//                    .process();
//        } catch (Exception e) {
//            UtilsLog.e("video_VideoProcessor===" + e);
//            UtilsLog.e("video_VideoProcessor===" + e.toString());
//            e.printStackTrace();
//        }
//    }

    class VideoCompressAsyncTask extends AsyncTask<String, String, String> {

        Context mContext;

        public VideoCompressAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... paths) {
            String filePath = null;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(paths[0]);
                String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
                String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
                double widths = Integer.parseInt(width) * 0.9;
                double heights = Integer.parseInt(height) * 0.9;
                int videoWidth = new Double(widths).intValue();
                int videoHeight = new Double(heights).intValue();
                filePath = SiliCompressor.with(mContext).compressVideo(paths[0], paths[1], videoHeight, videoWidth, 1200000);
                Log.e("tag", "压缩完成了老哥，要开始上传啦~~");
                Log.e("tag", "压缩后的路径为===" + filePath);
                if (filePath != null) {
                    String logStr = "视频压缩完成，即将开始上传=======";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    getDataUploadVideo2(model, filePath, "");
                } else {
                    String logStr = "视频压缩失败=======";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return filePath;

        }

        //得到压缩好的路径
        @Override
        protected void onPostExecute(String compressedFilePath) {
            super.onPostExecute(compressedFilePath);

        }
    }

    void siliCompressor(String videoUriString, String videoPath, final VideoUploadModel model) {
        String foder = Environment.getExternalStorageDirectory() + "/compress/";
        Log.e("tag", "压缩视频的文件夹为：" + foder);
        File file = new File(foder);
        if (!file.exists()) {
            file.mkdirs();
        }
        new VideoCompressAsyncTask(this).execute(videoUriString, file.getPath());
//        StringfilePath= SiliCompressor.with(BaseApplication.getSelf()).compressVideo(videoPath, destinationDirectory，outWidth，outHeight，bitrate);参数传入原视频videoPath和压缩后destinationDirectory存放的文件夹，返回压缩后图片绝对路径。横屏视频的outWidth宽度   outHeight高度   bitrate比特率（码率）越高数据大  体积越大一般450000
    }

    void videoCompress_medium(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoMedium(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress_high(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoHigh(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress_no(VideoUploadModel model2) {
        getDataUploadVideo(model2, false, "");
    }

    void videoCompress_low(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoLow(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress(String videoUriString, String videoPath, final VideoUploadModel model2) {
//        VideoSlimmer.convertVideo(videoUriString, videoPath, 480, 800, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {

//               VideoSlimmer.convertVideo(videoUriString, videoPath, 480, 480, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {
        String logStrqw = "\n" + "first---外检上传视频--onStartCommand--" +
                "\n" + "carsInforModel:" + model2.toString() + "\n"
                + "SharedPreferencesUtils.getDongBeiVersion(this):" + SharedPreferencesUtils.getDongBeiVersion(this) + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());

        VideoSlimmer.convertVideo(videoUriString, videoPath, 800, 800, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish(boolean result) {
                UtilsLog.e("videoCompress---视频路径=onFinish=" + result);
//                //convert finish,result(true is success,false is fail)
                String logStrqw = "\n" + "first---外检上传视频--videoCompress--onFinish--" +
                        "\n" + "result:" + result + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
                if (result) {
                    getDataUploadVideo(model2, true, "");
                }
            }

            @Override
            public void onProgress(float percent) {
                UtilsLog.e("videoCompress---视频路径=onProgress=" + percent);
                String logStrqw = "\n" + "first---外检上传视频--videoCompress--onProgress--" +
                        "\n" + "percent:" + String.valueOf(percent) + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
            }
        });
    }

    void videoCompress2(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoMedium(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                UtilsLog.e("onStart==" + str);
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                UtilsLog.e("onSuccess==" + str);
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = String.valueOf(percent) + "%";
                UtilsLog.e("onProgress====" + str);
            }
        });
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    //上传视频
    private void getDataUploadVideo(VideoUploadModel carsInforModel, boolean is, String currentOutputVideoPath) {
        String video_url_path = "";
        if (!TextUtils.isEmpty(currentOutputVideoPath)) {
            video_url_path = currentOutputVideoPath;
        } else {
            if (is) {
                video_url_path = carsInforModel.getZp();
            } else {
                video_url_path = carsInforModel.getSize();
            }
        }
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        String logStrqw = "\n" + "FirstActivity---外检上传视频--getDataUploadVideo--" +
                "\n" + "currentOutputVideoPath::" + currentOutputVideoPath + "\n"
                + "carsInforModel:" + carsInforModel.toString() + "\n"
                + "url:" + carsInforModel.getPath() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
        OkGo.<String>post(carsInforModel.getPath())
//                .isMultipart(true)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(video_url_path))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }

                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        String str = "totalSize:" + progress.totalSize +
                                "currentSize:" + progress.currentSize +
                                "date:" + progress.date +
                                "fraction:" + String.valueOf(progress.fraction) +
                                "exception:" + progress.exception;
                        UtilsLog.e("上传视频==uploadProgress====" + str);
                        UtilsLog.e("上传视频==uploadProgress====" + (progress.fraction * 100) + "%");
                        String logStr = "\n" + "上传视频==uploadProgress====" +
                                "\n" + "uploadProgress::" + str + "\n"
                                + "Progress::" + progress.toString();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        carsInforModel.setProgress(progress.fraction);
                        carsInforModel.save();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    //上传视频
    private void getDataUploadVideo2(final VideoUploadModel carsInforModel, String filePath, String currentOutputVideoPath) {
        String video_url_path = "";
        if (!TextUtils.isEmpty(currentOutputVideoPath)) {
            video_url_path = currentOutputVideoPath;
        } else {
            video_url_path = filePath;
        }
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        String logStrqw = "\n" + "FirstActivity---外检上传视频--getDataUploadVideo--" +
                "\n" + "currentOutputVideoPath::" + currentOutputVideoPath + "\n"
                + "carsInforModel:" + carsInforModel.toString() + "\n"
                + "url:" + carsInforModel.getPath() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
        OkGo.<String>post(carsInforModel.getPath())
//                .isMultipart(true)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(video_url_path))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }

                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        String str = "totalSize:" + progress.totalSize +
                                "currentSize:" + progress.currentSize +
                                "date:" + progress.date +
                                "fraction:" + String.valueOf(progress.fraction) +
                                "exception:" + progress.exception;
                        UtilsLog.e("上传视频==uploadProgress====" + str);
                        UtilsLog.e("上传视频==uploadProgress====" + (progress.fraction * 100) + "%");
                        String logStr = "\n" + "上传视频==uploadProgress====" +
                                "\n" + "uploadProgress::" + str + "\n"
                                + "Progress::" + progress.toString();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        carsInforModel.setProgress(progress.fraction);
                        carsInforModel.save();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    //开启服务
    public void startService(String str) {
        //开启服务需要Intent对象,和Activity跳转类似
        Intent intent = new Intent(this, MyUploadService.class);
        intent.putExtra("service_data", str);
        startService(intent);

    }

    //开启服务
    public void startService(CarsInforModel model) {
        //开启服务需要Intent对象,和Activity跳转类似
        Intent intent = new Intent(this, MyUploadService.class);
        intent.putExtra("service_model", model);
        startService(intent);
    }

    //停止服务
    public void stopService() {
        //停止服务的方法
        stopService(new Intent(this, MyUploadService.class));
    }

    //绑定服务
    public void bindService() {
        //绑定服务
        bindService(new Intent(this, MyUploadService.class), conn, flags);
    }

    //解绑服务
    public void unBindService() {
        //防止在没有绑定的情况下，去解除绑定，抛出异常
        try {
            //解除绑定
            unbindService(conn);
        } catch (Exception e) {
            System.out.println("FFmpegActivity.unBindService" + e);
        }
    }

    //服务绑定的连接对象
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    //服务绑定的标识
    //BIND_AUTO_CREATE 绑定的同时，启动Service
    private int flags = Service.BIND_AUTO_CREATE;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionChecker.PERMISSION_REQUEST_CODE:
                if (permissionChecker.hasAllPermissionsGranted(grantResults)) {
                    // 执行你的相关操作
//                    if(type == 1){
//                        startAudio();
//                    }else if(type == 2){
//                        startVideo();
//                    }
                } else {
                    // 权限拒绝后的提示
                    permissionChecker.showDialog();
                }
                break;
        }
    }

    Uri fileUri = null;

    void luxiang() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        try {
            //fileUri=Uri.fromFile(createMediaFile());如果这样写会报错
            fileUri = FileProvider.getUriForFile(instance, getApplicationContext().getPackageName() + ".provider", createMediaFile());//这是正确的写法

        } catch (IOException e) {
            e.printStackTrace();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

        startActivityForResult(intent, 1);
    }

    private File createMediaFile() throws IOException {
        if (Utils.hasSdcard()) {
            if ((getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
                // 选择自己的文件夹
                String path = Environment.getExternalStorageDirectory().getPath() + "/myvideo/";
                // Constants.video_url 是一个常量，代表存放视频的文件夹
                File mediaStorageDir = new File(path);
                if (!mediaStorageDir.exists()) {
                    if (!mediaStorageDir.mkdirs()) {
                        Log.e("TAG", "文件夹创建失败");
                        return null;
                    }
                }
                // 文件根据当前的毫秒数给自己命名
                String timeStamp = String.valueOf(System.currentTimeMillis());
                timeStamp = timeStamp.substring(7);
                String imageFileName = "V" + timeStamp;
                String suffix = ".mp4";
                File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix);
                return mediaFile;
            }
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        UtilsLog.e("requestCode==" + requestCode);
        Uri Uri = data.getData();
        UtilsLog.e("Uri.toString()==" + Uri.toString());
        UtilsLog.e("Uri.getPath()==" + Uri.getPath());
        if (resultCode == 1 && null != data) {
//            Uri Uri = data.getData();
//            UtilsLog.e("Uri.toString()==" +Uri.toString());
//            UtilsLog.e("Uri.getPath()==" +Uri.getPath());
        }
    }


    @OnClick({R.id.ac_first_waijian, R.id.ac_first_dipandongtai,
            R.id.ac_first_lushi, R.id.ac_first_setting,
            R.id.ac_first_denglu, R.id.ac_first_diaodu,
            R.id.first_imageView, R.id.ac_first_yujian,
            R.id.ac_first_setting2, R.id.ac_first_tianjin,
            R.id.ac_first_qingdao, R.id.ac_first_qingdao2,
            R.id.ac_first_setting3
    })
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.ac_first_qingdao:
                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 8;
                break;
            case R.id.ac_first_qingdao2:
                break;
            case R.id.ac_first_tianjin:
                //   天津地区
                intent = new Intent(instance, TianjinActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                break;
            case R.id.ac_first_setting3:
                //   设置
                intent = new Intent(instance, SettingActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                break;
            case R.id.ac_first_yujian:
                //   天津地区--预检
                intent = new Intent(instance, PreChereckActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                break;
            case R.id.ac_first_waijian:
//                intent = new Intent(instance, LoginActivity.class);
                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                break;
            case R.id.ac_first_dipandongtai:
                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 2;
                break;
            case R.id.ac_first_lushi:
                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 1;
                break;
            case R.id.ac_first_setting:
                intent = new Intent(instance, DiaoDuActivity.class);
                BaseApplication.JIANCE_MODE = 7;
//                intent = new Intent(instance, WaiKuoListActivity.class);
//                intent = new Intent(instance, SettingActivity.class);
//                BaseApplication.JIANCE_MODE = 0;
//                intent = new Intent(instance, DaiJianCarsActivity.class);
//                BaseApplication.JIANCE_MODE = 6;
                break;
            case R.id.ac_first_setting2:
                //地沟
                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 6;
//                intent = new Intent(instance, WaiKuoListActivity.class);
//                intent = new Intent(instance, SettingActivity.class);
//                BaseApplication.JIANCE_MODE = 0;
//                intent = new Intent(instance, DaiJianCarsActivity.class);
//                BaseApplication.JIANCE_MODE = 6;
                break;
            case R.id.ac_first_diaodu:
//                //调度
                intent = new Intent(instance, DiaoDuActivity.class);
                BaseApplication.JIANCE_MODE = 7;
//                break;
//            case R.id.ac_first_digou_item:
//                intent = new Intent(instance, DaiJianCarsActivity.class);
//                BaseApplication.JIANCE_MODE = 6;
//                break;
        }
        if (intent != null) {
            intent.putExtra("check_mode", BaseApplication.JIANCE_MODE);
            intent.putExtra("login_UserID", Login_name);
            UtilsLog.e("getDataToLogin-login_IDNumber==" + login_IDNumber);
            intent.putExtra("login_IDNumber", login_IDNumber);
            startActivity(intent);
        }
//        switch (view.getId()) {
//            case R.id.first_imageView:
////                intent = new Intent(instance, OnlineActivity.class);
//                intent = new Intent(instance, CarActivity.class);
//                BaseApplication.JIANCE_MODE = 0;
//                break;
////            Intent intent3 = new Intent(LoginActivity.this, OnlineActivity.class);
////            startActivity(intent3);
//            case R.id.ac_first_waijian:
//                intent = new Intent(instance, LoginActivity.class);
//                BaseApplication.JIANCE_MODE = 0;
//                break;
//            case R.id.ac_first_dipandongtai:
//                intent = new Intent(instance, LoginActivity.class);
//                BaseApplication.JIANCE_MODE = 2;
//                break;
//            case R.id.ac_first_lushi:
//                intent = new Intent(instance, LoginActivity.class);
//                BaseApplication.JIANCE_MODE = 1;
//                break;
//            case R.id.ac_first_diaodu:
//                //调度
//                intent = new Intent(instance, LoginActivity.class);
//                BaseApplication.JIANCE_MODE = 3;
//                break;
//            case R.id.ac_first_denglu:
//                //登陆
//                intent = new Intent(instance, LoginActivity.class);
//                BaseApplication.JIANCE_MODE = 6;
//                break;
//            case R.id.ac_first_setting:
//                intent = new Intent(instance, SettingActivity.class);
//                break;
//        }
//        if (intent != null) {
//            startActivity(intent);
//        }
    }

    private long exitTime = 0;

    // 双击返回退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                logOut();
                BaseApplication.getSelf().exit(this);
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
//

    //退出登录
    private void logOut() {
        String logout_url = "/api/User/" + login_username + "/UserQuitID";
        UtilsLog.e("退出登录---url==" + SharedPreferencesUtils.getIP(instance) + logout_url);
        String logStr = "\n" + "退出登录----" + "\n" + "URL::" +
                SharedPreferencesUtils.getIP(instance) + logout_url + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        OkGo.<String>get(SharedPreferencesUtils.getIP(instance) + logout_url).tag(instance)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        WaitDialog.show(instance, "加载中...");
//                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
//                        UtilsLog.e("getDataUsersList-result==" + result);
//                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("退出登录-newResult==" + result);
//                        String logStr = "\n" + "获取用户列表--getDataUsersList----onSuccess" + "\n" + "URL::" +
//                                SharedPreferencesUtils.getIP(instances) +
//                                GETALLUSERS + "\n" + "result::" + result + "\n";
//                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        if (!TextUtils.isEmpty(newResult) && !"[[]]".equals(newResult) && !"[{}]".equals
//                                (newResult) && !"[]".equals(result)) {
//
//                            try {
//                                BaseApplication.userAccountModelList = JsonUtil.stringToArray(newResult,
//                                        UserAccountModel[].class);
//                                //0  3  4  6
//                                if (BaseApplication.userAccountModelList != null && BaseApplication.userAccountModelList.size() > 0) {
//
//                                }
//                            } catch (Exception e) {
//                                UtilsLog.e("退出登录t-Exception==" + e.getMessage());
//                            }
//                        } else {
////                            Toast.makeText(instances, getResources().getString(R.string.network_error),
//// Toast.LENGTH_LONG).show();
//                            UtilsLog.e("退出登录-result==" + "没有数据");
//                        }
                        WaitDialog.dismiss();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        WaitDialog.dismiss();
//                        CommonUtils.hideLoadingDialog(instances);
                        String logStr = "\n" + "退出登录----onError" + "\n" + "URL::" +
                                SharedPreferencesUtils.getIP(instance) +
                                logout_url + "\n" + "result::" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        UtilsLog.e("退出登录-onError==" + response.body());

//                        Toast.makeText(instances, "读取人员列表失败，请退出重试", Toast
//                                .LENGTH_LONG).show();
                    }
                });
    }


//    private void initFile() {
//        makeRootDirectory(PATH);
//        currentOutputVideoPath = PATH + GetPathFromUri.getVideoFileName();
//        //压缩后的视频地址
//        UtilsLog.e( "FirstActivity---压缩后的视频地址===" + currentOutputVideoPath);
//    }
//
//    private void initVideo() {
//        //真正的视频压缩初始化
//        mCompressor = new Compressor(this);
//        mCompressor.loadBinary(new InitListener() {
//            @Override
//            public void onLoadSuccess() {
//                UtilsLog.e( "FirstActivity---视频压缩初始化---load library succeed");
//            }
//
//            @Override
//            public void onLoadFail(String reason) {
//                UtilsLog.e( "FirstActivity---视频压缩初始化---load library fail:" + reason);
//            }
//        });
//    }

//
//    /**
//     * 视频压缩开始
//     *
//     */
//    private void startCompress(final VideoUploadModel model) {
//        String mVideoPath=model.getSize();
//        getVideoTime(mVideoPath);
//        try {
//            if (TextUtils.isEmpty(mVideoPath)) {
//                Toast.makeText(this, "请重新选择视频", Toast.LENGTH_SHORT).show();
////                finish();
//            } else {
//                File file = new File(currentOutputVideoPath);
//                if (file.exists()) {
//                    file.delete();
//                }
//                String cmd = "";
//                UtilsLog.e( "FirstActivity---startCompress=mVideoPath=" + mVideoPath);
//                if (videoGotation == 90 || videoGotation == 270) {//之前以为和旋转的角度有关系，原来
//                    UtilsLog.e( "FirstActivity---videoGotation=90");
//                    cmd = "-y -i " + mVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
//                            "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 480x800 -aspect 9:16 " + currentOutputVideoPath;
//                } else {
//                    UtilsLog.e( "FirstActivity---videoGotation=0");
//                    if (videoWidth > videoHeight) {
//                        cmd = "-y -i " + mVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
//                                "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 800x480 -aspect 16:9 " + currentOutputVideoPath;
//                    } else {
//                        cmd = "-y -i " + mVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
//                                "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 480x800 -aspect 9:16 " + currentOutputVideoPath;
//                    }
//                }
//                String str = "FirstActivity---压缩开始--Compressing..." + "\n"
//                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
//                        + "\n" + model.toString()+"startCompress=mVideoPath=" + mVideoPath + "\n" +
//                        "currentOutputVideoPath=="+currentOutputVideoPath+ "\n";
//                UtilsLog.e("FirstActivity---onStart==" + str);
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//                startTime = System.currentTimeMillis();
//                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
//                execCommand(cmd,model);
//            }
//        } catch (Exception e) {
//            UtilsLog.e( "FirstActivity---startCompress=e=" + e.getMessage());
//            String str = "FirstActivity---startCompress=e=..." + "\n"+ e.getMessage()+ "\n";
//            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//        }
//    }

//    private void execCommand(final String cmd,final VideoUploadModel model) {
//        File mFile = new File(currentOutputVideoPath);
//        if (mFile.exists()) {
//            mFile.delete();
//        }
//        UtilsLog.e( "FirstActivity---cmd= " + cmd);
//        mCompressor.execCommand(cmd, new CompressListener() {
//            @Override
//            public void onExecSuccess(String message) {
////                success input:/storage/emulated/0/myvideo/1648691854535.mp4,size:19.732645MB,
////                        output:/storage/emulated/0/apeng/android_2022040710454381251.mp4,size:3.8561773MB
////                if (mProcessingDialog!=null){
////                    mProcessingDialog.dismiss();
////                }
//                UtilsLog.e( "FirstActivity---压缩--success ---model.getSize()---" + model.getSize());
//                String result = getString(R.string.compress_result_input_output, model.getSize()
//                        , getFileSize(model.getSize()), currentOutputVideoPath, getFileSize(currentOutputVideoPath));
//                UtilsLog.e( "FirstActivity---压缩--success " + result);
//                UtilsLog.e( "FirstActivity---压缩--success--currentOutputVideoPath--- " + currentOutputVideoPath);
//                getDataUploadVideo(model,true,currentOutputVideoPath);
////                Toast.makeText(context, "success " + result, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onExecFail(String reason) {
//                UtilsLog.e( "FirstActivity---onExecFail--fail--压缩失败--- " + reason);
//                String str = "FirstActivity---压缩--onExecFail--fail--压缩失败---" + "\n"+ reason+ "\n";
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
////                Toast.makeText(context, "压缩失败", Toast.LENGTH_SHORT);
////                if (mProcessingDialog!=null){
////                    mProcessingDialog.dismiss();
////                }
////                finish();
//            }
//
//            @Override
//            public void onExecProgress(String message) {
//                try {
//                    String str = "FirstActivity---压缩--onExecProgress--message--" + "\n"+ message+ "\n";
//                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//                    UtilsLog.e( "FirstActivity---progress " + message);
//
//                    double switchNum = getProgress(message);
//                    if (switchNum == 10000) {
//                        //如果找不到压缩的片段，返回为10000
//                        String str2 = "FirstActivity---如果找不到压缩的片段，返回为10000--switchNum---" + "\n"+ switchNum+ "\n";
//                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str2.getBytes());
//                        UtilsLog.e( "FirstActivity---10000");
////                        if (mProcessingDialog!=null){
////                            mProcessingDialog.setProgress(0);
////                        }
//                    } else {
//                        UtilsLog.e( "FirstActivity---progress ===" + (int) (getProgress(message) / 10));
////                        if (mProcessingDialog!=null){
////                            mProcessingDialog.setProgress((int) (getProgress(message) / 10));
////                        }
//                    }
//                } catch (Exception e) {
////                    if (mProcessingDialog!=null){
////                        mProcessingDialog.dismiss();
////                    }
//                    String str = "FirstActivity---onExecProgress--压缩失败---" + "\n"+ e.getMessage()+ "\n";
//                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//                    UtilsLog.e( "FirstActivity---onExecProgress--e=" + e.getMessage());
//                }
//            }
//        });
//    }

    /**
     * 获取视频的时长
     */
    void getVideoTime(String mVideoPath) {
        try {
            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(mVideoPath);
            videoTime = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);//获取视频时长
            videoWidth = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));//获取视频的宽度
            videoHeight = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));//获取视频的高度
            videoGotation = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));//获取视频的角度

            UtilsLog.e("FirstActivity---videoWidth=" + videoWidth);
            UtilsLog.e("FirstActivity---videoHeight=" + videoHeight);

//            MyLog.i(TAG, "videoTime=" + videoTime);
//            mBitMap = retr.getFrameAtTime();
            videoLength = Double.parseDouble(videoTime) / 1000.00;
            UtilsLog.e("FirstActivity---videoLength=" + videoLength);

        } catch (Exception e) {
            e.printStackTrace();
            UtilsLog.e("FirstActivity---异常错误==e=" + e.getMessage());
            videoLength = 0.00;
//            finish();
//            Toast.makeText(this, "异常错误", Toast.LENGTH_SHORT);
        }

    }

    /**
     * 没有文件夹。创建文件夹
     *
     * @param filePath
     */
    public void makeRootDirectory(String filePath) {
        UtilsLog.e("FirstActivity---makeRootDirectory=");
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                Boolean isTrue = file.mkdir();
                UtilsLog.e("FirstActivity---istrue=" + isTrue + "");
            }
        } catch (Exception e) {

        }
    }

    /**
     * 进度条，只能是整形，所以max为1000，最少为0
     *
     * @param source
     * @return
     */
    double getProgressNum = 0.0;

    private double getProgress(String source) {
        if (source.contains("too large")) {//当文件过大的时候，会会出现 Past duration x.y too large
            UtilsLog.e("FirstActivity---too large");
            return getProgressNum;
        }
        Pattern p = Pattern.compile("00:\\d{2}:\\d{2}");
        Matcher m = p.matcher(source);
        if (m.find()) {
            //00:00:00
            String result = m.group(0);
            String temp[] = result.split(":");
            double seconds = Double.parseDouble(temp[1]) * 60 + Double.parseDouble(temp[2]);
            if (0 != videoLength) {
                getProgressNum = seconds / videoLength * 1000;
                return seconds / videoLength * 1000;
            }
            if (seconds == videoLength) {
                return 1000;
            }
        }
//        MyLog.i(TAG, "!m.find()="+getProgressNum);
        return 10000;//出现异常的时候，返回为10000
//      return 0;//出现异常的时候，显示上一个进度条
    }

    private String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            long size = f.length();
            return (size / 1024f) / 1024f + "MB";
        }
    }
}
